<?php
session_start();

if(!isset($_SESSION['last_key'])) {
  echo '{"error_code":0, "error":"Not logged in"}';
  return;
}

include_once('config.php');
include_once('weibooauth.php');

$c = new WeiboClient(WB_AKEY, WB_SKEY, $_SESSION['last_key']['oauth_token'], $_SESSION['last_key']['oauth_token_secret']);

// action types
const FWD    = 'fwd';
const CMT    = 'cmt';
const LOGOUT = 'exit';
const DELETE = 'del';
const UPDATE = 'up';
const UNREAD = 'un';

$action = $_GET['action'];
$msgid = $_GET['msgid'];
$text = ($_GET['text']); // urlencode

if ($action == FWD) {
  $msg = $c->repost($msgid, $text);
} elseif ($action == CMT) {
  $msg = $c->send_comment($msgid, $text, null);
} elseif ($action == LOGOUT) {
  $msg = $c->end_session(); // destory all sessions
  $_SESSION['last_key'] = NULL;
  unset($_SESSION['last_key']);
} elseif ($action == DELETE) {
  $msg = $c->destroy($msgid);
} elseif ($action == UPDATE) {
  $msg = $c->update($text);
} elseif ($action == UNREAD) {
  $msg = $c->get_unread();
} else {
  $msg['error_code'] = -1;
  $msg['error'] = 'Unknown command';
}

if (isset($msg['error_code']) && isset($msg['error'])){
  echo '{"error_code":'.$msg['error_code'].', "error":"'.$msg['error'].'"}';
} else {
  echo '{"action":"'.$action.'"}';
}
?>